<?php
declare (strict_types = 1);

namespace app\middleware;

use app\helpers\jwt_token;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class wxAuthMiddleware
{
    /**
     * @param $request
     * @param \Closure $next
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 9:09
     * @return mixed|\think\response\Json
     * 处理请求
     */
    public function handle($request, \Closure $next)
    {
        $jwt_token = new jwt_token();
        //
        $header = $request->header();
        if (!isset($header['token'])){
            return json(['code' => 10000,'msg'=>'request must with token']);
        }
        $token = $header['token'];
        try {
            $token = (new Parser())->parse($token);
        }catch (\Exception $exception){
            return json(['code' => 10001,'msg'=>'invalid token']);
        }
        $singer = new Sha256();
        $token->verify($singer,'_@xgjd^1#096&24%2020');
        if(!$token->verify($singer,'_@xgjd^1#096&24%2020')){
            return json(['code' => 10003,'msg'=>'token verify failed']);
        }
        $data = new ValidationData();
        if(!$token->validate($data)){
            $request->wx_user_id = $token->getClaim('uid');
            $token = $jwt_token->createToken($token->getClaim('uid'));
            return json(['code' => 10004,'msg'=>'token expired','token'=>$token]);
        }
        $request->wx_user_id = $token->getClaim('uid');
        return $next($request);
    }
}
